"""
FastAPI应用主文件

Home Cloud API 应用程序的主入口文件，提供：
- FastAPI应用实例创建和配置
- 中间件配置（CORS、异常处理）
- 路由注册和管理
- 生命周期管理
- 静态文件服务
"""

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
import uvicorn
from contextlib import asynccontextmanager
import os
import traceback

# 导入API路由
from apis.user_api import router as user_router
from apis.role_api import router as role_router
from apis.permission_api import router as permission_router
from apis.captcha_api import router as captcha_router
from apis.widget_api import router as widget_router
from db.session import db_manager


@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    应用程序生命周期管理
    
    管理应用程序的启动和关闭过程，包括：
    - 启动时初始化数据库连接
    - 关闭时清理数据库连接
    
    Args:
        app: FastAPI应用实例
    """
    # 启动时初始化数据库连接
    await db_manager.init_db()
    print("数据库连接已初始化")

    yield

    # 关闭时清理数据库连接
    await db_manager.close_db()
    print("数据库连接已关闭")


# 创建FastAPI应用实例
app = FastAPI(
    title="Home Cloud API",
    description="Home Cloud Management System API",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan,
)

# 配置CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.exception_handler(HTTPException)
async def http_exception_handler(_request, exc):
    """
    HTTP异常处理器
    
    Args:
        _request: 请求对象
        exc: HTTP异常
        
    Returns:
        JSONResponse: 错误响应
    """
    return JSONResponse(status_code=exc.status_code, content={"error": exc.detail})


@app.exception_handler(Exception)
async def general_exception_handler(_request, exc):
    """
    通用异常处理器
    
    Args:
        _request: 请求对象
        exc: 异常对象
        
    Returns:
        JSONResponse: 服务器错误响应
    """
    print("Unhandled Exception:")
    traceback.print_exc()
    return JSONResponse(status_code=500, content={"error": "Internal server error"})


@app.get("/", summary="根路径重定向")
async def root():
    """
    根路径重定向到API文档
    
    Returns:
        RedirectResponse: 重定向到文档页面
    """
    return RedirectResponse(url="/docs", status_code=302)


@app.get("/docs", summary="Swagger UI")
async def swagger_ui():
    """
    自定义 Swagger UI 页面
    
    Returns:
        FileResponse: Swagger UI HTML文件
    """
    return FileResponse("static/swagger/index.html")


@app.get("/health", summary="健康检查")
async def health_check():
    """
    应用程序健康检查
    
    Returns:
        dict: 健康状态
    """
    return {"status": "healthy"}


# 挂载静态文件目录
app.mount("/static", StaticFiles(directory="static"), name="static")

# 手动注册路由，确保角色和权限API正确加载
app.include_router(user_router, prefix="/api")
app.include_router(role_router, prefix="/api")
app.include_router(permission_router, prefix="/api")
app.include_router(captcha_router, prefix="/api")
app.include_router(widget_router, prefix="/api")

# 注册组件路由
from widgets import apis as widget_apis
for router in widget_apis:
    app.include_router(router, prefix="/api")

# 自动加载其他API路由
from apis import apis
for router in apis:
    # 避免重复注册
    if router not in [user_router, role_router, permission_router, captcha_router, widget_router]:
        app.include_router(router, prefix="/api")

if __name__ == "__main__":
    """
    应用程序启动入口
    
    启动开发服务器
    """
    uvicorn.run("main:app", host="0.0.0.0", port=8001, reload=True)
